package cn.lvji.springboot.learn2.controller;

import cn.lvji.springboot.learn2.vo.ScenicVO;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * rest controller
 *
 * @author zhouzx
 */
@RestController
class ScenicRestController implements CommandLineRunner {
    private Map<Long, ScenicVO> map;

    @GetMapping("/scenic/list")
    public List<ScenicVO> get() {
        List<ScenicVO> list = new ArrayList<>(map.size());
        Set<Map.Entry<Long, ScenicVO>> set = map.entrySet();
        Iterator<Map.Entry<Long, ScenicVO>> it = set.iterator();
        while (it.hasNext()) {
            list.add(it.next().getValue());
        }
        return list;
    }

    @PostMapping("/scenic/")
    public ResponseEntity<String> saveFormData(ScenicVO scenic) {
        map.put(scenic.getId(), scenic);
        return ResponseEntity.ok().body("ok");
    }

    @PostMapping("/scenic/json")
    public ResponseEntity<String> saveJson(@RequestBody ScenicVO scenic) {
        map.put(scenic.getId(), scenic);
        return ResponseEntity.ok().body("ok");
    }

    @GetMapping("/scenic/{id}")
    public ScenicVO get(@PathVariable("id") Long id) {
        return map.get(id);
    }

    @DeleteMapping("/scenic/{id}")
    public ResponseEntity<String> delete(@PathVariable Long id) {
        map.remove(id);
        return ResponseEntity.ok().body("ok");
    }

    @GetMapping("/test/req")
    public String testR(HttpServletRequest req, HttpServletResponse res) {
        return "s";
    }

    @PutMapping("/scenic")
    public ResponseEntity<String> update(ScenicVO scenic) {
        ScenicVO db = map.get(scenic.getId());
        BeanUtils.copyProperties(scenic, db);
        return ResponseEntity.ok().body("ok");
    }

    @PatchMapping("/scenic/down/{id}")
    public ResponseEntity<String> down(@PathVariable Long id) {
        map.get(id).setStatus(2);
        return ResponseEntity.ok().body("ok");
    }


    /**
     * 启动执行方法
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        map = new HashMap<>(10);
        for (int i = 0; i < 10; i++) {
            ScenicVO scenic;
            if (i % 2 == 0) {
                scenic = new ScenicVO((long) i, "name" + i, 1, "美景", "广东广州");
            } else {
                scenic = new ScenicVO((long) i, "name" + i, 2, "美景", "广东广州");
            }
            map.put((long) i, scenic);
        }
    }
}

